<?php
/**
 *抽奖
 * wsl
 * 2022/7/17
 */
namespace App\Http\Service;

class LotteryService
{
    /**
     * @param $prize_arr_data
     * @return array
     * 抽奖接口
     */
    public static function Lottery($prize_arr_data)
    {
        foreach ($prize_arr_data as $k => $value){
            $prize_arr[$k] = ['id' => $value->id , 'prize' => $value->store_name,'inventory'=>$value->integral_inventory];
        }
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['inventory'];//概率数组
        }
        $rid = self::get_rand($arr); //根据概率获取奖项id
        $res['yes'] = $prize_arr[$rid-1]['prize']; //中奖项
        unset($prize_arr[$rid-1]); //将中奖项从数组中剔除，剩下未中奖项
        shuffle($prize_arr); //打乱数组顺序
        if($res['yes']!='无'){
            $result['status']=1;
            $result['name']='恭喜你抽中：'.$res['yes'];
        }else{
            $result['status']=-1;
            $result['msg']='恭喜您，未中奖';
        }
        return $result;
    }

    /**
     * @param $proArr
     * @return int|string
     * 计算中奖概率
     */
    public static function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);  //返回随机整数
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
}
